import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import CaptchaImage from '../../src/components/CaptchaImage';

type RootStackParamList = {
  Youzhao: undefined;
  Xinmi: {
    username?: string;
    from?: 'Youzhao' | 'Shouzhao';
  };
  Daohang: undefined;
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'Youzhao'>;

const EmailRecoveryScreen = () => {
  const navigation = useNavigation<NavigationProp>();
  const [account, setAccount] = useState('');
  const [bindEmail, setBindEmail] = useState('');
  const [captcha, setCaptcha] = useState('');
  const [inputCaptcha, setInputCaptcha] = useState('');
  const [emailCode, setEmailCode] = useState('');
  const [isEmailBtnDisabled, setIsEmailBtnDisabled] = useState(true);
  const [isFormValid, setIsFormValid] = useState(false);
  const [accountError, setAccountError] = useState('');
  const [captchaError, setCaptchaError] = useState('');
  const [emailError, setEmailError] = useState('');

  // 校验邮箱格式
  const validateEmail = (text: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text);
  const validateQQEmail = (text: string) => /^\w+([-+.']\w+)*@qq\.com$/.test(text);

  // 校验表单
  const validateForm = () => {
    const isAccountValid = account.length > 0;
    const isBindEmailValid = validateQQEmail(bindEmail);
    const isCaptchaValid = inputCaptcha.toUpperCase() === captcha;
    const isEmailCodeValid = emailCode.length === 6;
    setAccountError(isAccountValid ? '' : '账号不能为空');
    setEmailError(isBindEmailValid ? '' : '请输入正确的@qq.com邮箱');
    setCaptchaError(isCaptchaValid ? '' : '验证码错误');
    setIsFormValid(isAccountValid && isBindEmailValid && isCaptchaValid && isEmailCodeValid);
    setIsEmailBtnDisabled(!isBindEmailValid);
  };

  // 图形验证码变化
  const handleCaptchaChange = (newCaptcha: string) => {
    setCaptcha(newCaptcha);
    validateForm();
  };

  // 发送邮件验证码
  const handleSendEmailCode = async () => {
    if (!validateEmail(bindEmail)) {
      Alert.alert('请输入正确的邮箱');
      return;
    }
    // 这里可以调用后端接口发送邮件验证码
    Alert.alert('验证码已发送', '请注意查收邮箱');
  };

  // 下一步
  const handleSubmit = () => {
    if (isFormValid) {
      navigation.navigate('Xinmi', {
        username: account,
        from: 'Youzhao'
      });
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backBtn} onPress={() => navigation.goBack()}>
          <Text style={styles.backBtnText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>邮箱找回</Text>
      </View>
      <View style={styles.form}>
        {accountError ? <Text style={styles.errorText}>{accountError}</Text> : null}
        <TextInput
          style={[styles.input, accountError ? styles.inputError : null]}
          placeholder="请输入登录账号"
          placeholderTextColor="#bbb"
          value={account}
          onChangeText={text => {
            setAccount(text);
            validateForm();
          }}
          onBlur={validateForm}
        />
        {emailError ? <Text style={styles.errorText}>{emailError}</Text> : null}
        <TextInput
          style={[styles.input, emailError ? styles.inputError : null]}
          placeholder="请输入与账号绑定的邮箱"
          placeholderTextColor="#bbb"
          value={bindEmail}
          onChangeText={text => {
            setBindEmail(text);
            validateForm();
          }}
          onBlur={validateForm}
        />
        {captchaError ? <Text style={styles.errorText}>{captchaError}</Text> : null}
        <View style={styles.captchaContainer}>
          <TextInput
            style={[styles.input, styles.captchaInput, captchaError ? styles.inputError : null]}
            placeholder="请输入图形验证码"
            placeholderTextColor="#bbb"
            value={inputCaptcha}
            onChangeText={text => {
              setInputCaptcha(text);
              validateForm();
            }}
            onBlur={validateForm}
          />
          <CaptchaImage onCaptchaChange={handleCaptchaChange} />
        </View>
        <View style={styles.captchaContainer}>
          <TextInput
            style={[styles.input, styles.captchaInput]}
            placeholder="请输入邮箱验证码"
            placeholderTextColor="#bbb"
            value={emailCode}
            onChangeText={text => {
              setEmailCode(text);
              validateForm();
            }}
            onBlur={validateForm}
          />
          <TouchableOpacity
            style={[styles.emailBtn, isEmailBtnDisabled && styles.emailBtnDisabled]}
            onPress={handleSendEmailCode}
            disabled={isEmailBtnDisabled}
          >
            <Text style={{ color: isEmailBtnDisabled ? '#999' : '#fff' }}>发送邮件</Text>
          </TouchableOpacity>
        </View>
        <TouchableOpacity
          style={[styles.submitBtn, !isFormValid && styles.submitBtnDisabled]}
          onPress={handleSubmit}
          disabled={!isFormValid}
        >
          <Text style={[styles.submitBtnText, !isFormValid && styles.submitBtnTextDisabled]}>下一步</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    marginBottom: 10,
    position: 'relative',
  },
  backBtn: {
    position: 'absolute',
    left: 10,
    top: 0,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
    zIndex: 1,
  },
  backBtnText: {
    fontSize: 22,
    color: '#333',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  form: {
    paddingHorizontal: 20,
    flex: 1,
    top: 50,
  },
  input: {
    height: 40,
    backgroundColor: '#f5f5f5',
    borderRadius: 5,
    paddingHorizontal: 10,
    marginBottom: 15,
    fontSize: 14,
  },
  captchaContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  captchaInput: {
    flex: 1,
    marginRight: 10,
    marginBottom: 0,
  },
  emailBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 12,
  },
  emailBtnDisabled: {
    backgroundColor: '#cccccc',
  },
  submitBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  submitBtnDisabled: {
    backgroundColor: '#cccccc',
  },
  submitBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  submitBtnTextDisabled: {
    color: '#666666',
  },
  errorText: {
    color: '#d32f2f',
    fontSize: 12,
    marginBottom: 5,
    marginLeft: 5,
  },
  inputError: {
    borderColor: 'red',
    borderWidth: 1,
  },
});

export default EmailRecoveryScreen;
